<template>
  <div class="w-full">
    <!-- 表格区域 -->
    <el-table :data="userlist" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="账号" prop="account"></el-table-column>
      <el-table-column label="头像" prop="avatar"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="角色" prop="roles"></el-table-column>
      <el-table-column label="上次登录" prop="last">
        <template slot-scope="scope">
          {{ $moment(scope.last).fromNow() }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="enabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            @change="userStateChanged(scope.row)"
            :disabled="scope.row['account'] === account"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            icon="el-icon-refresh-right"
            size="mini"
            @click="handleResetPass(scope.row['_id'])"
          ></el-button>
          <!-- 删除角色按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deletUser(scope.row['_id'])"
            v-if="scope.row['account'] !== account"
          ></el-button>
          <!-- 分配角色按钮 
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="false"
          >
            <el-button
              @click="setRole(scope.row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
            ></el-button>
          </el-tooltip>
          -->
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-pagination
      layout="total, prev, pager, next"
      background
      :page-size="10"
      @size-change="handleSizeChange"
      :total="total"
      @current-change="handleCurrentChange"
      style="text-align: center; margin-top: 20px"
    >
    </el-pagination>

    <!-- 分配角色的对话框-->
    <el-dialog
      @close="setRoleClose"
      title="分配角色"
      :visible.sync="setRoledialogVisible"
      width="50%"
    >
      <user-role></user-role>
    </el-dialog>
  </div>
</template>


<script>
import { mapGetters } from "vuex";
import { users, removeUser, updateUser, resetPass } from "@/api/user";
import UserRole from "./UserRole.vue";

export default {
  components: {
    UserRole,
  },
  computed: {
    ...mapGetters(["account"]),
  },
  props: ["index", "keyword"],
  data() {
    return {
      setRoledialogVisible: false,

      userInfo: {},
      selectedRoleId: "",
      rolesList: [],

      page: 1,
      pagesize: 10,
      userlist: [],
      total: 0,
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async deletUser(id) {
      const confirmInfo = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmInfo !== "confirm") return this.$message.info("已取消删除");
      else {
        removeUser({ id }).then((res) => {
          this.getUserList();
          this.$message.success("已成功删除");
        });
      }
    },

    async handleResetPass(id) {
      resetPass(id).then((res) => {
        this.$message.success("密码已重置");
      });
    },

    async getUserList() {
      users({
        type: this.index,
        flag: false,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        this.total = res.data.total;
        this.userlist = res.data.users;
      });
    },
    handleSizeChange(newSize) {
      this.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.getUserList();
    },
    async userStateChanged(userInfo) {
      updateUser({
        id: userInfo["_id"],
        enabled: userInfo.enabled,
      }).then((res) => {
        this.$message.success("更新用户状态成功！");
      });
    },

    async setRole(userinfo) {
      this.userInfo = userinfo;
      //在展示对话框之前获取所有角色的列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取用户角色失败！");
      }
      this.$message.success("获取用户角色成功！");
      this.rolesList = res.data;
      this.setRoledialogVisible = true;
    },
    //点击按钮分配角色
    async saveRole() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }
      // console.log(this.userInfo.id);
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("更新用户角色成功！");
      this.setRoledialogVisible = false;

      this.getUserList();
    },

    setRoleClose() {
      this.selectedRoleId = "";
      this.userInfo = {};
    },
  },
};
</script>

